<template>
  <div class="sys-ellipsis">
    <el-tooltip ref="tooltip" v-bind="tooltipProps">
      <div class="sys-ellipsis__tooltip--content" slot="content" v-if="subContent" v-html="subContent"></div>
    </el-tooltip>

    <div ref="content"
         class="sys-ellipsis__content"
         :style="`-webkit-line-clamp: ${lines}`"
         @mouseenter="handleMouseEnter"
         @mouseleave="handleMouseLeave">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import ElTooltip from 'element-ui/lib/tooltip'
import {debounce} from '../utils/util'

export default {
  name: 'sys-ellipsis',
  props: {
    ...ElTooltip.props,
    lines: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      tooltipContent: ''
    }
  },
  methods: {
    handleMouseEnter() {
      const content = this.$refs.content

      const range = document.createRange()
      range.setStart(content, 0)
      range.setEnd(content, content.childNodes.length)
      const rangeHeight = range.getBoundingClientRect().height

      if(rangeHeight > content.offsetHeight || content.scrollHeight > content.offsetHeight) {
        const tooltip = this.$refs.tooltip
        tooltip.referenceElm = content
        tooltip.$refs.popper && (tooltip.$refs.popper.style.display = 'none')
        tooltip.doDestroy()
        tooltip.setExpectedState(true)

        this.activeTooltip(tooltip)
      }
    },
    handleMouseLeave() {
      const tooltip = this.$refs.tooltip
      if(tooltip) {
        tooltip.setExpectedState(false)
        tooltip.handleClosePopper()
      }
    },
    update() {
      this.tooltipContent = this.$slots.default[0].elm.outerHTML
    }
  },
  computed: {
    tooltipProps() {
      const props = {...this.$props}
      delete props.lines
      if(!props.placement) {
        props.placement = 'top'
      }
      return props
    },
    subContent() {
      if(!this.tooltipProps.content) {
        if(this.$slots.default[0].tag) {
          return this.tooltipContent
        } else {
          return this.$slots.default[0].text
        }
      }
      return null
    }
  },
  mounted() {
    this.tooltipContent = this.$slots.default[0].elm.outerHTML
    this.activeTooltip = debounce(tooltip => tooltip.handleShowPopper(), 50)
  }
}
</script>

<style lang="scss" scoped>
.sys-ellipsis {
  &__content {
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
}
</style>
